package fgin

import (
	"errors"
	"fmt"
	"log"
	"net/http"

	"gitee.com/wu-jin-feng/fgin/fgin_plugs/fotel"
	"github.com/gin-gonic/gin"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

// opentelemetry 初始化
func initOpentelemetry() {
	// 初始化链路追踪部分
	if fginConfig.Otel.TracerHttp != "" {
		err := fotel.InitTracer(fginConfig.Otel.TracerHttp, fginConfig.ServiceName)
		if err != nil {
			panic(err)
		}
	}
	// 初始化监控部分 prometheus
	if fginConfig.Otel.PrometheusAddress != "" {
		err := fotel.InitMeterProvider()
		if err != nil {
			panic(err)
		}
		// 开启监听服务
		if fginConfig.NetType == "grpc" {
			switch fginConfig.Env {
			case "pro":
				// 生产模式
				gin.SetMode(gin.ReleaseMode)
			case "dev":
				// 调试模式
				gin.SetMode(gin.DebugMode)
			default:
				panic(errors.New("env配置错误,只支持:pro生产模式,dev调试模式"))
			}
		}
		// 如果没有配置路由 使用默认： /metrics
		if fginConfig.Otel.PrometheusRoute == "" {
			fginConfig.Otel.PrometheusRoute = "/metrics"
		}
		prometheusRouter := gin.New()
		prometheusRouter.GET(fginConfig.Otel.PrometheusRoute, gin.WrapH(promhttp.Handler()))
		prometheusSrv := &http.Server{
			Addr:    fginConfig.Otel.PrometheusAddress,
			Handler: prometheusRouter,
		}
		go func() {
			// 服务连接
			logSuger.Info(fmt.Sprintf("开启otel prometheus服务get请求接口: %s%s\n", fginConfig.Otel.PrometheusAddress, fginConfig.Otel.PrometheusRoute))
			if err := prometheusSrv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
				log.Fatalf("otel prometheus服务 listen err: %v\n", err)
			}
		}()
	}
}
